//
//  PhoneNumViewController.m
//  jingdongfang
//
//  Created by 郝志宇 on 16/9/1.
//  Copyright © 2016年 ZhiYu Hao. All rights reserved.
//

#import "PhoneNumViewController.h"
#import "NSString+Extension.h"
#import "MeViewController.h"
#import "IGBindPhoneApi.h"
#import "IGCommonApi.h"
#import "addGalleryViewController.h"
#import "IGCaptchaView.h"

@interface PhoneNumViewController ()<UITextFieldDelegate>{
    NSInteger timer;
    NSString *password;
}
@property (weak, nonatomic) IBOutlet UITextField *phoneNumTextField;
@property (weak, nonatomic) IBOutlet UITextField *verCodeTextField;
@property (weak, nonatomic) IBOutlet UIButton *getCodeBtn;
@property (strong, nonatomic) IBOutlet UITextField *pwCodeTextField;
@property (weak, nonatomic) IBOutlet UIButton *confirmBtn;
@property (nonatomic,strong) IGBindPhoneApi *bindPhoneApi;
@property (nonatomic, strong) IGCommonApi *commonApi;

@end

@implementation PhoneNumViewController
#pragma mark -生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
    
    //    self.title = @"绑定手机号码";
    self.title = NSLocalizedString(@"Link your mobile", nil);
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(userDidTakeScreenshot) name:UIApplicationUserDidTakeScreenshotNotification object:nil];
    
    self.phoneNumTextField.delegate=self;
    self.verCodeTextField.delegate=self;
    self.pwCodeTextField.keyboardType = UIKeyboardTypeAlphabet;
    self.pwCodeTextField.secureTextEntry = YES;
    [self.getCodeBtn setTitleColor:[UIColor appColor] forState:UIControlStateNormal];
    [self.getCodeBtn setTitleColor:[UIColor c5Color] forState:UIControlStateDisabled];
    self.getCodeBtn.enabled = NO;
    [self.getCodeBtn addTarget:self action:@selector(getCodeBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.phoneNumTextField addTarget:self action:@selector(phoneNumChange:) forControlEvents:UIControlEventEditingChanged ];
    [self.verCodeTextField addTarget:self action:@selector(verNumChange:) forControlEvents:UIControlEventEditingChanged ];
    [self.pwCodeTextField addTarget:self action:@selector(pwNumChange:) forControlEvents:UIControlEventEditingChanged ];
    
    [self.confirmBtn setBackgroundColor:[UIColor c5Color]];
    self.confirmBtn.layer.cornerRadius=20.f;
    self.confirmBtn.enabled=NO;
    
    if (self.thirdLoginFirst) {//隐藏返回按钮
        [self ig_setupLeftBarButtonItemWithTitle:@"" image:nil highLightedImage:nil];
    }
}

- (void)ig_rightButtonPressed:(id)sender {
    [UIViewController ig_pushViewControllerClass:[addGalleryViewController class] animated:YES];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}
- (IBAction)confirmBtnClick:(id)sender {
    if (self.phoneNumTextField.text.length==0) {
        [self presentMessageTips:NSLocalizedString(@"Please Input Mobile Number for Binding", nil)];
        return;
    } else if (![self.phoneNumTextField.text isTelephone]) {
        [self presentMessageTips:NSLocalizedString(@"Please Input Correct Mobile No.", nil)];
        return;
    }
    
    if (self.verCodeTextField.text.length==0) {
        [self presentMessageTips:NSLocalizedString(@"Please Input Verification Code", nil)];
        
        return;
    }
    
    if(self.pwCodeTextField.text.length==0){
        [self presentMessageTips:NSLocalizedString(@"Please Input Password", nil)];
        
        return;
    } else if(self.pwCodeTextField.text.length<6||self.pwCodeTextField.text.length>16){
        [self presentMessageTips:NSLocalizedString(@"Please Input 6-16 Digits or Characters", nil)];
        
        return;
    }
    
    password=self.pwCodeTextField.text;
    //    password=[NSString md5_32Bit:password];
    self.bindPhoneApi = [IGBindPhoneApi new];
    self.bindPhoneApi.phone = self.phoneNumTextField.text;
    self.bindPhoneApi.smsCode = self.verCodeTextField.text;
    self.bindPhoneApi.pwd = password;
    self.bindPhoneApi.type = @"1";
    __weak typeof(self) weakSelf = self;
    [self.bindPhoneApi startWithDecodeClass:[IGBlindResp class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
        if (responseObject) {
            [weakSelf presentMessageTips:NSLocalizedString(@"Linked Successfully", nil)];
            [IGUser saveTel:weakSelf.phoneNumTextField.text];
            if (weakSelf.thirdLoginFirst) {
                [UIViewController ig_pushViewControllerClass:[addGalleryViewController class] animated:YES];
            } else {
                [weakSelf.navigationController popViewControllerAnimated:YES];
            }
        }
    }];
}

-(void)phoneNumChange:(UITextField *)textField{
    [self.getCodeBtn setEnabled:NO];
    if ([self.phoneNumTextField.text isTelephone]) {
        [self.getCodeBtn setEnabled:YES];
    }
}
-(void)verNumChange:(UITextField *)textField{
    [self.confirmBtn setEnabled:NO];
    [self.confirmBtn setBackgroundColor:[UIColor c5Color]];
    if (self.verCodeTextField.text.length>0) {
        [self.confirmBtn setEnabled:YES];
        [self.confirmBtn setBackgroundColor:[UIColor appColor]] ;
    }
}
-(void)pwNumChange:(UITextField *)textField{
    [self.confirmBtn setEnabled:NO];
    [self.confirmBtn setBackgroundColor:[UIColor c5Color]];
    if (self.pwCodeTextField.text.length>0) {
        [self.confirmBtn setEnabled:YES];
        [self.confirmBtn setBackgroundColor:[UIColor appColor]] ;
    }
}

- (IBAction)getCodeBtnClick:(id)sender {
    [self getCode];
}

- (void)getCode{
    [self.view endEditing:YES];
    NSString *phoneNum = self.phoneNumTextField.text;
    if (phoneNum.length==0) {
        [self presentMessageTips:NSLocalizedString(@"Please Input Mobile Number", nil)];
        return;
    } else if (![phoneNum isTelephone]) {
        [self presentMessageTips:NSLocalizedString(@"Please Input Correct Mobile No.", nil)];
        return;
    }
    __weak typeof(self) weakSelf = self;
    [IGCaptchaView num:self.phoneNumTextField.text showCaptcha:^(NSString *cap) {
        [weakSelf getRealCode:cap];
    }];
}

- (void)getRealCode:(NSString *)code {
    [self showText:NSLocalizedString(@"Sending...", nil)];
    
    timer = 60;
    self.commonApi = [[IGCommonApi alloc] init];
    self.commonApi.apiType = IGiGalleryApiTypeMemberGetPhoneSMSNew;
    self.commonApi.phone = self.phoneNumTextField.text;
    self.commonApi.code = code;
    __weak typeof(self) weakSelf = self;
    [self.commonApi startWithDecodeClass:[IGCommonResp class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
        if (responseObject) {
            dispatch_async(dispatch_get_main_queue(), ^{
                //                [weakSelf presentMessageTips:@"发送成功"];
                [weakSelf presentMessageTips:NSLocalizedString(@"Sent Successfully", nil)];
                weakSelf.getCodeBtn.userInteractionEnabled = NO;
                //                NSString *title = [NSString stringWithFormat:@"%@s重发", @(timer)];
                NSString *title = [NSString stringWithFormat:@"%@ sec", @(timer)];
                [weakSelf.getCodeBtn setTitle:title forState:UIControlStateNormal];
                [weakSelf.getCodeBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
                
                [NSTimer scheduledTimerWithTimeInterval:1 target:weakSelf selector:@selector(timerDown:) userInfo:weakSelf.getCodeBtn repeats:YES];
            });
        }
    }];
}

- (void)timerDown:(NSTimer *)time {
    timer--;
    //    NSString *title = [NSString stringWithFormat:@"%@s重发", @(timer)];
    NSString *title = [NSString stringWithFormat:@"%@ s", @(timer)];
    [self.getCodeBtn setTitle:title forState:UIControlStateNormal];
    [self.getCodeBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    if (timer == 0) {
        self.getCodeBtn.userInteractionEnabled = YES;
        [self.getCodeBtn setTitle:NSLocalizedString(@"Acquire", nil) forState:UIControlStateNormal];
        [self.getCodeBtn setTitleColor:[UIColor appColor] forState:UIControlStateNormal];
        [time invalidate];
    }
}

- (void)userDidTakeScreenshot {
    [UIAlertView bk_showAlertViewWithTitle:@"" message:NSLocalizedString(@"You mobile screen is captured.\n Please pay attention to password security.", nil) cancelButtonTitle:NSLocalizedString(@"Confirm",nil) otherButtonTitles:nil handler:^(UIAlertView *alertView, NSInteger buttonIndex) {
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
